package com.tdcoding.chat.action;

import com.tdcoding.chat.action.common.ActionContext;
import com.tdcoding.chat.constants.ChatConstants;
import com.tdcoding.chat.constants.MainConstants;
import com.tdcoding.chat.dbase.mapper.UserMapper;
import com.tdcoding.chat.entities.ChannelInfo;
import com.tdcoding.chat.entities.RequestInfo;
import com.tdcoding.chat.entities.UserInfo;
import com.tdcoding.chat.helper.Logger;
import com.tdcoding.chat.helper.SecurityHelper;
import com.tdcoding.chat.helper.StringHelper;
import com.tdcoding.chat.manager.ChatManager;
import com.tdcoding.chat.manager.DBManager;

import io.netty.channel.Channel;

public class CoreAction extends BaseAction {
	// /**
	// * 短信/语音验证
	// * @throws InvalidProtocolBufferException
	// */
	// public void getVerifyCode(Channel channel,BasePacket packet) throws
	// InvalidProtocolBufferException {
	// Logger.println(this, "getVerifyCode", packet);
	// long userId=packet.getUserId();
	// String packetId=packet.getPacketId();
	// GetVerifyCode codeReq=GetVerifyCode.parseFrom(packet.getParameters());
	// String userName = codeReq.getUserName();
	// int verifyMethod=codeReq.getVerifyMethod();
	// Logger.println(this, "getVerifyCode", userId,verifyMethod);
	// if (!StringHelper.hasValue(request)) {
	// ActionContext.writeResponse(channel,packetId, packet.getRequest(),-1,
	// "The lack of necessary parameters.");
	// return;
	// }
	// if (request.equals("register")) {
	// long result=DBForUser.existUser(userName);
	// if (result!=0) {
	// ActionContext.writeResponse(channel,packetId, packet.getRequest(),-1,
	// "The mobile phone number has been registered");
	// }
	// }
	// String content=null;
	// if (verifyMethod==0) {
	// content =TDCValidator.getInstance().sendMessage(userName);
	// }
	// else{
	//// content =TDCValidator.getInstance().sendVoice(phoneNo, displayNo,
	// verifyContent);
	// }
	// if (StringHelper.hasValue(content)) {
	// ActionContext.writeResponse(channel,packetId,packet.getRequest(), 0,
	// content);
	// } else
	// ActionContext.writeResponse(channel,packetId,packet.getRequest(), -1,
	// "");
	// }

	/**
	 * 注册 (0注册成功；-1用户已存在；-2注册失败)
	 * 
	 * @param channel
	 * @param requestInfo
	 */
	public void register(Channel channel, RequestInfo requestInfo) {
		String packetId = requestInfo.getPacketId();
		Object[] parameters = requestInfo.getParameters();
		UserInfo userInfo = (UserInfo) parameters[0];
	
		// DeviceInfo deviceInfo=(DeviceInfo) parameters[1];
		UserMapper userMapper = DBManager.getSqlSession().getMapper(UserMapper.class);
		Long userId= userMapper.existUser(userInfo.getUserName());
		if (userId!=null&&userId >=1000) {
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(),-1,
					"This account has been registered");
			return;
		}
		userInfo.setUserId( StringHelper.getUniqueId(0));
		userInfo.setUserLevel(0);
		userInfo.setUserStatus(0);
		userInfo.setIdentity(0);
		userInfo.setAllowAdd(0);
		userInfo.setLplatform(0);
		userInfo.setRplatform(0);
		int result = userMapper.register(userInfo);
		DBManager.doCommit();
		Logger.println(this, "register", result,userInfo);
		// DBForUser.addDeviceInfo(userId,userInfo.getUserName(),deviceInfo);
//		ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), result, "");
	}

	/**
	 * 登录 0：登录成功 ；-1：用户不存在 ；-2：密码错误 ；-3：用户未激活 ；-4：用户已冻结
	 */
	public void login(Channel channel, RequestInfo requestInfo) {
		Logger.println(this, "login", requestInfo);
		int platform = requestInfo.getPlatform();
		String packetId = requestInfo.getPacketId();
		Object[] parameters = requestInfo.getParameters();
		String password = SecurityHelper.encryptSHA(parameters[0].toString());
//		DeviceInfo deviceInfo = (DeviceInfo) parameters[1];
		UserMapper mapper = DBManager.getSqlSession().getMapper(UserMapper.class);
		UserInfo userInfo = mapper.login(requestInfo.getUserName());

		if (userInfo == null) {
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), -1,"");
			return;
		}
		if (!userInfo.getPassword().equals(password)) {
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), -2, "");
			return;
		}
		if (userInfo.getUserStatus() == 0) {
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), -3, "");
			return;
		}
		if (userInfo.getUserStatus() == -1) {
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), -4, "");
			return;
		}

		long userId = userInfo.getUserId();
		ChannelInfo channelInfo = ChatManager.getChannelInfo(userId);
		if (channelInfo != null&&channelInfo.getChatChannel()!=null) {
			Logger.println(this, "login conflict", platform, channelInfo.getPlatform());
			if (platform == channelInfo.getPlatform()) {
				String currIP = channelInfo.getChatChannel().localAddress().toString();
				String newIP = channel.localAddress().toString();
				Logger.println(this, "login conflict~", currIP, newIP);
				if (!currIP.equals(newIP)) {
					ActionContext.writeResponse(channelInfo.getChatChannel(), packetId, ChatConstants.CONFLICT, -1,
							"Login conflict");
					ChatManager.removeChannelInfo(MainConstants.CHANNEL_TYPE_ALL, userId);
				}
			}
		} else {
			channelInfo = new ChannelInfo();
			channelInfo.setStatus(0);
			channelInfo.setUserId(userId);
			channelInfo.setPlatform(platform);
			channelInfo.setUserName(requestInfo.getMethod());
			channelInfo.setPassword(password);
		}
		// 保存设备信息
		ChatManager.addChannelInfo(channel, channelInfo);
		// DBForUser.addDeviceInfo(userId,requestInfo.getMethod(),deviceInfo);
		ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), 0, 0);
	}

	/**
	 * 更新在线状态
	 */
	public void updateStatus(Channel channel, RequestInfo requestInfo) {
		Logger.println(this, "updateStatus", requestInfo);
		long userId = requestInfo.getUserId();
		String packetId = requestInfo.getPacketId();
		Object[] parameters = requestInfo.getParameters();
		int status = Integer.parseInt(parameters[0].toString());
		ChannelInfo channelInfo = ChatManager.updateChannelInfo(userId, status);
		if (channelInfo != null) {
			ActionContext.dispatchMyStatus(userId, status);// 通知所有好友本人状态
		} else
			ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), -1, "");
	}

	/**
	 * 注销登录
	 */
	public void logout(Channel channel, RequestInfo requestInfo) {
		Logger.println(this, "logout", requestInfo);
		long userId = requestInfo.getUserId();
		String packetId = requestInfo.getPacketId();
		ActionContext.writeResponse(channel, packetId, requestInfo.getMethod(), 0, "");
		ChatManager.removeChannelInfo(MainConstants.CHANNEL_TYPE_ALL, userId);
	}

}
